package com.qall.configserver.service.impl;



import com.alibaba.dubbo.config.annotation.Service;
import com.qall.configability.entity.GetConfigRequest;
import com.qall.configserver.event.EventObject;
import com.qall.configability.service.DataService;
import com.qall.configserver.util.FileUtil;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;


import javax.annotation.Resource;

import java.util.Map;

@Component
@Service
public class DataServiceImpl implements DataService {
    @Resource
    private FileUtil fileUtil;

    @Resource
    private ApplicationEventPublisher applicationEventPublisher;

    /**
     * @param nameSpace 域
     * @param appName     应用名称
     * @param data      应用数据
     */
    public void updateData(@NonNull String nameSpace, @Nullable String appName, @NonNull Map<String, String> data) {
        // update common config
        if (appName == null) {
            fileUtil.writeCommonConfigToFile(nameSpace, data);
        } else {
            fileUtil.writeNodeConfigToFile(appName, nameSpace, data);
        }
        //  mark the config is change
        EventObject eventObject = new EventObject();
        eventObject.setAppName(appName);
        eventObject.setNameSpace(nameSpace);
        applicationEventPublisher.publishEvent(eventObject);
    }

    public Map<String, String> getConfig(GetConfigRequest request) {

        return fileUtil.getConfig(request.getNameSpace(), request.getAppName());
    }

    public Map<String, String> getConfigByAppName(String nameSpace, String appName) {

        return fileUtil.getConfig(nameSpace, appName);
    }

}
